package org.example.rowing.service;

import lombok.extern.slf4j.Slf4j;
import org.example.rowing.domain.Race;
import org.example.rowing.domain.RoundScore;
import org.example.rowing.mapper.RaceMapper;
import org.example.rowing.mapper.RoundScoreMapper;
import org.example.rowing.vo.RaceVO;
import org.example.rowing.vo.RoundScoreVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class RaceInfoService {

    @Autowired
    private RaceMapper raceMapper;
    @Autowired
    private RoundScoreMapper roundScoreMapper;

    public List<RaceVO> showRacesByBoatType(String boatType) {
        List<RaceVO> raceVOS = raceMapper.selectRaceVOByBoatType(boatType);
        return raceVOS;
    }

    public void saveOrUpdateRace(Race race) {
        if (race.getId() == null) {
            raceMapper.insertRace(race);
            log.info("新比赛项目已保存: {}", race);
        } else {
            raceMapper.updateRace(race);
            log.info("比赛项目已更新: {}", race);
        }
    }

    public void deleteRace(Long id) {
        Race race = new Race();
        race.setId(id);
        List<Race> races = raceMapper.selectRaceByConditions(race);
        if (races != null && !races.isEmpty()) {
            raceMapper.deleteRace(id);
            log.info("比赛项目已删除: {}", id);
        } else {
            log.info("此比赛项目暂不存在!!!");
        }
    }

    public List<RoundScoreVO> loadRoundScoreVOByRaceId(Long raceId) {
        return roundScoreMapper.selectRoundScoreVOByRaceId(raceId);
    }

    public void saveRoundScore(RoundScoreVO roundScoreVO) {
        RoundScore roundScore = new RoundScore(roundScoreVO.getRaceId(),
                roundScoreVO.getRound(), roundScoreVO.getLabelId(),
                roundScoreVO.getLane(), roundScoreVO.getScore(), roundScoreVO.getRegistrationVO().getRegistrationId(), roundScoreVO.getStatus());
        roundScoreMapper.saveRoundScore(roundScore);
    }

    public void saveRoundScore(RoundScore roundScore) {
        roundScoreMapper.saveRoundScore(roundScore);
    }

    public List<RoundScoreVO> showRoundScoreByCondition(RoundScoreVO roundScoreVOCondition) {
        List<RoundScoreVO> roundScoreVOS = new ArrayList<>();
        if (roundScoreVOCondition != null) {
            roundScoreVOS = roundScoreMapper.selectRoundScoreByCondition(roundScoreVOCondition);
        }
        return roundScoreVOS;
    }

    public List<RaceVO> showSearchedRaces(RaceVO raceConditions) {
        List<RaceVO> raceVOS = new ArrayList<>();
        if (raceConditions != null) {
            raceVOS = raceMapper.selectRaceVOByCondition(raceConditions);
        }
        return raceVOS;
    }

    public Race selectRaceById(Long raceId) {
        Race race = new Race();
        race.setId(raceId);
        List<Race> races = raceMapper.selectRaceByConditions(race);
        return races.get(0);
    }
}
